package log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import prefuse.data.Graph;
import prefuse.data.io.DataIOException;
import prefuse.data.io.GraphReader;
import prefuse.data.io.TreeMLReader.TreeMLHandler;
import prefuse.data.parser.ParserFactory;
import prefuse.util.io.IOLib;

public class TreeReader implements GraphReader {

	
	@Override
	public Graph readGraph(String location) throws DataIOException {
		try {
            InputStream is = IOLib.streamFromString(location);
            if ( is == null )
                throw new DataIOException("Couldn't find " + location
                    + ". Not a valid file, URL, or resource locator.");
            return readGraph(is);
        } catch ( IOException e ) {
            throw new DataIOException(e);
        }   
	}

	@Override
	public Graph readGraph(URL url) throws DataIOException {
        try {
            return readGraph(url.openStream());
        } catch ( IOException e ) {
            throw new DataIOException(e);
        }
	}

	@Override
	public Graph readGraph(File f) throws DataIOException {
        try {
            return readGraph(new FileInputStream(f));
        } catch ( FileNotFoundException e ) {
            throw new DataIOException(e);
        }
	}

	@Override
	public Graph readGraph(InputStream is) throws DataIOException {
		try {       
            TreeHandler    handler   = new TreeHandler();
            SAXParserFactory factory   = SAXParserFactory.newInstance();
            SAXParser        saxParser = factory.newSAXParser();
            saxParser.parse(is, handler);
            return handler.getTree();
        } catch ( Exception e ) {
            throw new DataIOException(e);
        }
	}

}
